package tacos.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import tacos.entity.Ingredient;
import tacos.entity.Order;
import tacos.entity.Taco;
import tacos.data.springData.IngredientRepository;
import tacos.data.springData.TacoRepository;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

//@Slf4j
@Controller
@RequestMapping("/design")
@SessionAttributes("order")
public class DesignTacoController {

    private final IngredientRepository ingredientRepository;

    private TacoRepository tacoRepository;

    @Autowired
    public DesignTacoController(IngredientRepository ingredientRepository, TacoRepository tacoRepository) {
        this.ingredientRepository = ingredientRepository;
        this.tacoRepository = tacoRepository;
    }

    @ModelAttribute(name = "order")
    public Order order() {
        return new Order();
    }

    @ModelAttribute(name = "taco")
    public Taco taco() {
        return new Taco();
    }

    @PostMapping
    public String processDesign(
            @Valid @ModelAttribute("design") Taco design,  Errors errors,
            @ModelAttribute Order order) {

        System.out.println(design);
        if (errors.hasErrors()) {
            System.out.println("表单提交数据校验不通过");
            return "redirect:/design";
        }

        Taco saved = tacoRepository.save(design);

        order.addDesign(saved);

//        log.info("Processing design:" + design);
        return "redirect:/orders/current";
    }

    @GetMapping
    public String showDesignForm(Model model) {

        // 查找配料表所有配料并添加到 列表中
        List<Ingredient> ingredients = new ArrayList<>();
        ingredientRepository.findAll().forEach(i -> ingredients.add(i));


        Ingredient.Type[] types = Ingredient.Type.values();
        for (Ingredient.Type type : types) {
            model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
        }

        model.addAttribute("design", new Taco());
        return "design";
    }

    // 通过 java的stream，将数据通过 type 过滤出来
    private List<Ingredient> filterByType(List<Ingredient> ingredients, Ingredient.Type type) {
        // Java 8 新特性  Stream
        return ingredients
                .stream()
                .filter( x -> x.getType().equals(type))
                .collect(Collectors.toList());
    }
}
